<?php
/**
 * Amazon每日订单
 * Date: 2023/12/15
 * Time: 11:50
 */

namespace App\Logic\Amazon\Api\Parse;


use App\Models\Amazon\AmazonOrderDay;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysCountry;

class GetXmlAllOrdersDataByOrderDateGeneral{

    public static function exe($lines,$accountId){

        ini_set('memory_limit', '200M');
        set_time_limit(0);

        $linesArr = json_decode(json_encode($lines),true);
        if(!is_array($linesArr))return 2;
        if(!$accountId)return 2;
        $i = 0;
        $count = 0;
        try{
            if ($linesArr['Message']) {
                foreach($linesArr['Message'] as $line){
                    $flag = self::_addReportData($line,$accountId);
                    $flag && $count++;
                    $i++;

                    //echo 'exec: '.$i.PHP_EOL;
                    sleep(1);
                }
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i == $count ? 1 : 2;
    }

    /**
     * @param $line
     * @param $accountId
     * @return bool
     */
    private static function _addReportData($line,$accountId){

        $country = $line['Order']['FulfillmentData']['Address']['Country'];
        $countryId = SysCountry::getIdByCountry($country);
        $marketplaceId = AmazonCountry::getMarketplaceIdByCountryId($countryId);

        $params = [
            'amazon_order_id' => $line['Order']['AmazonOrderID'],
            'purchase_date' => gmdate('Y-m-d H:i:s',strtotime($line['Order']['PurchaseDate'])),
            'marketplace_id' => $marketplaceId,
            'sales_channel' => $line['Order']['SalesChannel'],
            'order_status' => AmazonOrderDay::getOrderStatusIdByStr($line['Order']['OrderStatus']),
            'account_id' => $accountId,
            'day' => $line['Order']['PurchaseDate']
        ];

        $re = AmazonOrderDay::query()->create($params);
        return !$re ? false : true;
    }

}
